package com.capgemini.fs.app.ekms.persistence.dao.implementations;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.capgemini.fs.app.ekms.common.Constants;
import com.capgemini.fs.app.ekms.model.Forum;
import com.capgemini.fs.app.ekms.model.Topic;
import com.capgemini.fs.app.ekms.persistence.dao.ForumDAO;
import com.capgemini.fs.app.ekms.persistence.util.QueryHelper;

public class ForumDAOImpl extends BaseDAOHibernateImpl<Forum> implements
		ForumDAO {

	public void addForum(Forum forum) {
//		getHibernateTemplate().save(forum);
		save(forum);
	}

	@SuppressWarnings("unchecked")
	public Forum getForumByName(String name) {
		String hql = "from Forum f where f.name=?";
		List<Forum> list = (List<Forum>) getHibernateTemplate().find(hql, name);
		return list.isEmpty()?null:(Forum) list.get(0);
	}

	public List<Forum> getAllForums() {
		return findAll(Forum.class);
	}
    @SuppressWarnings("unchecked")
    public List<Forum> getAllActiveForum() {
        HibernateTemplate template = getHibernateTemplate();
        return template.findByNamedQueryAndNamedParam("getAllActiveForum","status",Constants.FORUM_STATUS_ACTIVE);
    }

    public Forum findByPrimaryKey(Serializable id) {
        return super.findByPrimaryKey(Forum.class, id);
    }
    @SuppressWarnings("unchecked")
    public List<Forum> queryForum(final String forumName, final Integer status) {

        List forumList = (List<Forum>) getHibernateTemplate().executeFind(new HibernateCallback() {

            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria c = session.createCriteria(Forum.class);
                if (!QueryHelper.isNullOrEmpty(forumName)) {
                    c.add(Restrictions.like("name", "%"+forumName + "%"));
                }
                if (!QueryHelper.isNullOrEmpty(status)) {
                    c.add(Restrictions.eq("status", status));
                }
                
                c.setCacheable(true);
                return c.list();
            }

        });

        return forumList;

    }

	@SuppressWarnings("unchecked")
	public List<Topic> queryForumTopics(int forumId) {
		String hql="from Topic t where t.author.id=?";
		List<Topic> topics=(List<Topic>)getHibernateTemplate().find(hql,forumId);
		return topics.isEmpty()?null:topics;
	}
    
    
}
